package com.lone.yebserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lone.yebserver.pojo.Menu;
import com.lone.yebserver.pojo.MenuRole;
import com.lone.yebserver.pojo.RespBean;
import com.lone.yebserver.pojo.Role;
import com.lone.yebserver.service.IMenuRoleService;
import com.lone.yebserver.service.IMenuService;
import com.lone.yebserver.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Lone
 */
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;

    @ApiOperation(value = "查询所有角色")
    @GetMapping("/")
    public RespBean getAllRoles() {
        return RespBean.success("success", roleService.list());
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role) {
        if (!role.getName().startsWith("ROLE")) {
            role.setName("ROLE_" + role.getName());
        }

        if (roleService.save(role)) {
            return RespBean.success("success");
        }
        return RespBean.error("failed");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deleteRole(@PathVariable("rid") Integer rid) {
        if (roleService.removeById(rid)) {
            return RespBean.success("delete success");
        }
        return RespBean.error("delete failed");
    }

    @ApiOperation(value = "获取所有菜单")
    @GetMapping("/menus")
    public RespBean getAllMenus() {
        List<Menu> allMenus = menuService.getAllMenus();
        return RespBean.success("success", allMenus);
    }

    @ApiOperation(value = "根据角色ID查询菜单ID")
    @GetMapping("/mid/{rid}")
    public RespBean getMidByRid(@PathVariable("rid") Integer rid) {
        List<Integer> mids = menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid))
                .stream()
                .map(MenuRole::getMid)
                .collect(Collectors.toList());
        return RespBean.success("success", mids);
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
